<style lang="less" scoped>
@import "@/assets/style/variables.less";

.banner {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    padding: @padd;
    position: relative;

    .banner-form {
        margin-top: 15px;
    }

    .eltable {
        border-radius: 5px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        margin-top: 20px;
    }

    .block {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 30px;
    }

    .banner-form,
    .banner-table {
        .opt {
            margin-bottom: 15px;
        }

        .preview-img {
            width: 360px;
            height: 180px;
        }

        .el-upload-list {
            display: none;
        }


    }

    .my-input {
        width: 100% !important;
        height: 28px;
        line-height: 28px;
        -webkit-appearance: none;
        background-color: #FFF;
        background-image: none;
        border: 1px solid #DCDFE6;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: inherit;
        height: 40px;
        line-height: 40px;
        outline: 0;
        padding: 0 15px;
        transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
        width: 100%;
        border-radius: 4px;
    }
}
</style>
<template>
    <div class="banner">
        <div class="banner-header">
            <el-button size="small" :type="num == 1 ? 'danger' : ''" @click="num = 1">添加随笔</el-button>
            <el-button size="small" :type="num == 2 ? 'danger' : ''" @click="num = 2">随笔列表</el-button>
        </div>
        <div v-if="num == 1" class="banner-form">
            <div class="opt">
                <el-input v-model="myNoteText" placeholder="请输入随笔"></el-input>
            </div>
            <div class="opt">
                <el-button type="primary" @click="publishNoteFn">点击添加</el-button>
            </div>
        </div>
        <div v-if="num == 2" class="banner-table">
            <el-table border class="eltable" :data="tableData" style="width: 100%">
                <el-table-column align="center" label="序号" width="80">
                    <template slot-scope="scope">
                        <span>{{ scope.$index + 1 }}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="ID" prop="id" width="80"></el-table-column>

                <el-table-column align="center" label="随笔" prop="note_text"></el-table-column>
                <el-table-column align="center" label="日期" prop="createAt"></el-table-column>

                <el-table-column align="right">
                    <template slot="header">
                        <input type="text" placeholder="关键字" class="my-input" v-model="search">
                    </template>
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-popover style="margin-left: 10px;" placement="top" width="160"
                            v-model="visiblePopover[scope.$index]" trigger="click">
                            <p>确定删除这条随笔吗？</p>
                            <div style="text-align: right; margin: 0">
                                <el-button size="mini" type="text" @click="closePopover(scope.$index)">取消</el-button>
                                <el-button type="primary" size="mini"
                                    @click="removeNoteFn(scope.row.id, scope.$index)">确定</el-button>
                            </div>
                            <el-button slot="reference" type="danger" size="mini">删除</el-button>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="num == 2" class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="5"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <div>
            <el-dialog title="修改随笔" :visible.sync="centerDialogVisible" width="30%" center>
                <div>
                    <div class="opt">
                        <el-input v-model="text" placeholder="请输入随笔"></el-input>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button @click="modifyNoteFn(id, text)" type="primary">保存修改</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
// import { Message, MessageBox } from 'element-ui';
import { Message } from 'element-ui';
import { listNote, searchNote, publishNote, modifyNote, removeNote } from '../api/index'


export default {
    data() {
        return {
            visiblePopover: [],
            // 修改弹窗
            centerDialogVisible: false,
            // 添加随笔的文本
            myNoteText: '',
            tableData: [
                // {
                //     id: 1,
                //     note_text: "随笔1",
                //     createAt: '2021-01-01'
                // },
            ],
            search: '',// 用于获取输入框的值
            num: 2,
            text: "",//记录修改的标题
            id: "",//广告的唯一标记
            // 评论的总数
            total: 0,
            // 前往的页数
            currentPage: 1,
            // 当前的页码
            page_num: 1,
            // 获取的页数
            page_size: 5,

            timer: null,
            timer2: null

        }
    },
    // 组件销毁前清理定时器
    beforeDestroy() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
        if (this.timer2) {
            clearTimeout(this.timer2);
        }
    },
    methods: {
        // 搜索随笔
        async searchNoteFn(keyword) {
            if (keyword == '' || keyword == null) {
                await this.listNoteFn()
                return
            }
            await searchNote({ keyword })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.tableData = res.result.map(item => {
                                item.createAt = this.formatime(item.createAt)
                                return item;
                            })
                            this.total = res.result.length
                            Message({
                                showClose: true,
                                message: res.msg,
                                type: 'success',
                                offset: 100
                            })
                        } else {
                            Message({
                                showClose: true,
                                message: res.msg,
                                type: 'error',
                                offset: 100
                            })
                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '服务器错误',
                            type: 'error',
                            offset: 100
                        })
                        console.log(err)
                    }
                )
        },
        // 关闭删除弹窗
        closePopover(index) {
            this.$set(this.visiblePopover, index, false);
        },

        // 删除随笔

        async removeNoteFn(id, index) {
            if (id == '' || id == null || id == undefined) {
                Message({
                    showClose: true,
                    message: '请选择要删除的随笔',
                    type: 'error',
                    offset: 100
                })
                this.closePopover(index);
                return false;
            }
            await removeNote({ id })
                .then(
                    res => {

                        if (res.code == 200) {
                            Message({
                                showClose: true,
                                message: '删除成功',
                                type: 'success',
                                offset: 100
                            });
                            this.closePopover(index);
                            this.listNoteFn()
                        } else {
                            Message({
                                showClose: true,
                                message: '删除失败',
                                type: 'error',
                                offset: 100
                            });
                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '删除失败',
                            type: 'error',
                            offset: 100
                        });
                        console.log(err)
                    }
                )
        },
        // 修改随笔
        async modifyNoteFn(id, note_text) {
            if (note_text.trim() == '' || note_text == null) {
                Message({
                    showClose: true,
                    message: '你还没输入呢~~',
                    type: 'error',
                    offset: 100
                });
                return
            }
            await modifyNote({ id, note_text })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            Message({
                                showClose: true,
                                message: '修改成功',
                                type: 'success',
                                offset: 100
                            });
                            this.listNoteFn()
                            this.centerDialogVisible = false
                        } else {
                            Message({
                                showClose: true,
                                message: '修改失败',
                                type: 'error',
                                offset: 100
                            });
                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '修改失败',
                            type: 'error',
                            offset: 100
                        });
                        console.log(err)
                    }
                )
        },

        // 发布随笔

        async publishNoteFn() {
            if (this.myNoteText.trim() == '') {
                Message({
                    showClose: true,
                    message: '你还没输入呢~~',
                    type: 'error',
                    offset: 100
                });
                return
            }
            let note_text = this.myNoteText
            await publishNote({ note_text })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            Message({
                                showClose: true,
                                message: '添加成功',
                                type: 'success',
                                offset: 100
                            });
                            this.listNoteFn()
                            if (this.timer2) {
                                clearTimeout(this.timer2)
                            }
                            this.timer2 = setTimeout(() => {
                                this.num = 2
                                this.myNoteText = ''
                                this.timer2 = null;
                            }, 500)
                        } else {
                            Message({
                                showClose: true,
                                message: '添加失败',
                                type: 'error',
                                offset: 100
                            });
                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '添加失败',
                            type: 'error',
                            offset: 100
                        });
                        console.log(err)
                    }
                )
        },
        // 获取随笔分页列表
        async listNoteFn() {

            await listNote({ page_num: this.page_num, page_size: this.page_size }).then(
                res => {
                    if (res.code == 200) {
                        this.tableData = res.result.map(item => {
                            item.createAt = this.formatime(item.createAt)
                            return item
                        })
                        this.total = res.total
                    }
                    // console.log('222', Array(res.result.length).fill(false))
                    this.$set(this, 'visiblePopover', Array(res.result.length).fill(false))
                    // console.log(this.tableData)
                }, err => {
                    console.log(err)
                }
            )
        },
        // 编辑
        handleEdit(row) {
            // console.log(row);
            // 显示对话框
            this.centerDialogVisible = true;
            this.text = row.note_text
            this.id = row.id
        },
        // 删除
        async handleDelete() {
            this.visible = true
        },
        // 分页
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.page_size = val
            this.page_num = 1;
            this.listNoteFn()
        },
        // 当前的页数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.page_num = val
            this.currentPage = val;
            this.listNoteFn()
        }
    },
    // 初始化
    created() {
        this.listNoteFn()
    },
    watch: {
        $route: {
            immediate: true,
            deep: true,
            handler(newRoute) {
                // console.log(newRoute);
                this.$store.commit("addTab", newRoute);
            }
        },
        // 观察输入框的变化
        search: function (newKeyword) {
            // 执行搜索方法
            // console.log(newKeyword);
            let keyword = newKeyword
            // 清除之前的定时器
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                this.searchNoteFn(keyword)
                this.timer = null
            }, 500)

        }

    }
}
</script>